package com.iring.util.vos;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.Assert;

import com.iring.domain.config.prop.VOSCustomerProperties;
import com.iring.util.common.JacksonUtil;


/**
 * 请求vos http工具类
 *
 * @author wanggan
 */
@Configuration
@ConditionalOnBean({ VOSCustomerProperties.class, HttpComponentsClientHttpRequestFactory.class })
public class VOSDataUtil {

    private static final Logger logger = LoggerFactory.getLogger(VOSDataUtil.class);

    @Autowired
    VOSCustomerProperties vosCustomerProperties;

    @Autowired
    private HttpComponentsClientHttpRequestFactory httpRequestFactory;

    public String postData(String path, Object object)  {
        return postData(path, JacksonUtil.toJSon(object));
    }

    public String postData(String path, String jsonstr)  {
        String url = vosCustomerProperties.getUrl();
        Assert.notNull(url, "url must not be null");

        logger.info("request vos relative url={},data={}",path,jsonstr);
        StringBuilder sb = new StringBuilder();
        ClientHttpResponse httpResponse = null;
        try {
            URI uri = new URI(url + path);
            Assert.notNull(httpRequestFactory, "'httpRequestFactory' must not be null");
            ClientHttpRequest httpRequest = httpRequestFactory.createRequest(uri, HttpMethod.POST);

            HttpHeaders headers = httpRequest.getHeaders();
            headers.set("Content-Type", "application/json;charset=UTF-8");
            if (jsonstr != null) {
                httpRequest.getBody()
                        .write(jsonstr.getBytes());
            }
            httpResponse = httpRequest.execute();
            BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getBody()));
            br.lines()
                    .forEach((line) -> {
                        sb.append(line);
                    });
            if(httpResponse.getStatusCode()== HttpStatus.OK){
                return sb.toString();
            }
        } catch (Exception e) {
            logger.info("request vos exception={}",e);
        } finally {
            if (httpResponse != null) {
                httpResponse.close();
            }
        }
        return null;
    }
}
